package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.message.ErrorMessage;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        //校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            //无效手机号
            return Result.fail(ErrorMessage.PHONE_NUMBER_ERROR);
        }
        //生成验证码（6位数字）
        String code = RandomUtil.randomNumbers(6);
        //发送验证码
        //TODO: 后续完成验证码发送
        log.info("code:{}", code);
        //将验证码存储到redis中,并设置验证码的有效期为2分钟
        stringRedisTemplate.opsForValue().
                set(RedisConstants.LOGIN_CODE_KEY + phone, code,
                        RedisConstants.LOGIN_CODE_TTL, TimeUnit.MINUTES);

        //返回结果
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //1.校验手机号
        String phone = loginForm.getPhone();
        if (RegexUtils.isPhoneInvalid(phone)) {
            //无效手机号
            return Result.fail(ErrorMessage.PHONE_NUMBER_ERROR);
        }
        //2.校验验证码
        //从redis中获取code
        String cacheCode = stringRedisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY + phone);
        if (cacheCode == null || !cacheCode.equals(loginForm.getCode())) {
            return Result.fail(ErrorMessage.CODE_ERROR);
        }
        //3.根据手机号查询用户是否存在
        User user = query().eq("phone", phone).one();
        if (user == null) {
            //4.不存在，创建用户，并保存到数据库
            user = createUserWithPhone(phone);
        }
        //5.存在，保存用户信息到redis中,注意不要暴露用户信息，只保存部分信息
        String token = UUID.randomUUID().toString(true);
        String loginKey = RedisConstants.LOGIN_USER_KEY + token;
        //将用户的数据封装为map
        Map<String, String> userMap = new HashMap<>();
        userMap.put("Id", user.getId().toString());
        userMap.put("Icon", user.getIcon());
        userMap.put("NickName", user.getNickName());
        stringRedisTemplate.opsForHash().putAll(loginKey, userMap);
        //设置有效期为30分钟
        stringRedisTemplate.expire(loginKey, RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
        //6.返回token，让前端每次携带token
        return Result.ok(token);
    }

    @Override
    public Result sign() {
        //获取用户id
        Long userId = UserHolder.getUser().getId();
        //获取当前日期
        LocalDate now = LocalDate.now();
        String keySuffix = now.format(DateTimeFormatter.ofPattern("yyyyMM"));
        //拼接key
        String key = RedisConstants.USER_SIGN_KEY + userId + ":" + keySuffix;
        //写入redis
        stringRedisTemplate.opsForValue().setBit(key, now.getDayOfMonth() - 1, true);
        return Result.ok();
    }

    @Override
    public Result signCount() {
        //获取用户id
        Long userId = UserHolder.getUser().getId();
        //获取当前日期
        LocalDate now = LocalDate.now();
        String keySuffix = now.format(DateTimeFormatter.ofPattern("yyyyMM"));
        //拼接key
        String key = RedisConstants.USER_SIGN_KEY + userId + ":" + keySuffix;
        int dateOfMonth = now.getDayOfMonth();
        //获取用户的签到情况
        List<Long> signList = stringRedisTemplate.opsForValue().bitField(key,
                BitFieldSubCommands.create().
                        get(BitFieldSubCommands.BitFieldType.unsigned(dateOfMonth))
                        .valueAt(0));
        if (signList == null ||signList.isEmpty()){
            return Result.ok(0);
        }
        Long num = signList.get(0);
        if (num == null || num == 0){
            return Result.ok(0);
        }
        int count = 0;
        while(true){
            if((num & 1) == 0){
                break;
            }
            count ++;
            num >>>= 1;
        }
        return Result.ok(count);
    }

    private User createUserWithPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName(SystemConstants.USER_NICK_NAME_PREFIX + RandomUtil.randomString(6)); // 设置随机昵称
        save(user);
        return user;
    }
}
